package lab03.text03;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 在某目录下创建一个文本文件test.txt，
 * 通过字节输出流向文件中写入“Beijing欢迎你！”，
 * 通过字节输入流读出文件中的内容并显示；
 * 如果在已有文件中再追加
 * “我的学号是：你自己的学号”如何实现？
 */
public class Text {
    public static void main(String[] args) {
        //字节流写文件
        String path="D:\\test.txt";
        String value="Beijing欢迎你！！";
        FileOutputStream fileOutputStream=null;

        try {
            fileOutputStream=new FileOutputStream(path);
            fileOutputStream.write(value.getBytes());

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {

            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //读文件
        FileInputStream fileInputStream=null;
//        try {
//            fileInputStream=new FileInputStream(path);
//            int tmp;
//            //一次读一个字节
//            while ((tmp=fileInputStream.read())!=-1){
//                System.out.print((char) tmp);
//            }
        try {
            fileInputStream = new FileInputStream(path);
            byte[] data = new byte[fileInputStream.available()];    //新建一个字节数组
            fileInputStream.read(data);
            String s = new String(data);
            System.out.println(s);     //将数组转换为字符串输出.

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {

            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //在已有文件中写入内容
        path="D:\\test.txt";
        FileOutputStream file = null;
        try {
            file = new FileOutputStream(path);
            file.write(new String("我的学号是：你自己的学号").getBytes());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                file.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
